var app = getApp();
const api = require('../../api.js');
const select_options = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
const xhUploader = require('../../utils/qiniuUploader.js');
import Dialog from '../../component/vant/dialog/dialog';
import Toast from '../../component/vant/toast/toast';
var WxParse = require('../../component/wxParse/wxParse.js');
const util = require('../../utils/util.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    downloadUrl: api.xh.downloadDomain,
    question_html: api.xh.domain,
    courseware_type: {
      mp4: 'video',
      mp3: 'music',
      jpg: 'img',
      JPG: 'img',
      png: 'img',
      PNG: 'img',
      jpeg: 'img',
      JPEG: 'img',
      pic: 'img',
      PIC: 'img',
      gif: 'img',
      GIF: 'img',
      doc: 'word',
      DOC: 'word',
      docx: 'word',
      xlsx: 'excel',
      xls: 'excel',
      ppt: 'ppt',
      pptx: 'ppt',
      pdf: 'pdf',
      swf: 'flash',
      txt: 'other',
      box: 'other'
    },
    question_total: 0,
    currentTab: 0,
    questions: [],
    if_commit: 1,
    select_options: select_options,
    files: [],
    picture_list: [],
    file_list: [],
    replyArr: [],
    // 触摸开始时间
    touchStartTime: 0,
    // 触摸结束时间
    touchEndTime: 0,
    // 最后一次单击事件点击发生时间
    lastTapTime: 0,
    // 单击事件点击后要触发的函数
    lastTapTimeoutFunc: null,
    isIPX: app.globalData.isIPX
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var page = this;
    var standard_id = options.standard_id;
    var standard_name = options.standard_name;

    page.setData({
      standard_id: standard_id
    });
    app.setPageTitle(standard_name);
    // var options = {
    //   region: 'SCN', // 华北区
    //   uptokenURL: app.api.xh.upTokenUrl,
    //   domain: app.api.xh.domain,
    //   shouldUseQiniuFileName: false
    // };
    // xhUploader.init(options);

    // app.sendRequest({
    //   url: app.api.xh.upTokenUrl,
    //   success: res => {
    //     page.setData({
    //       uploadToken: res.token
    //     });
    //   }
    // });
    this.getResList();
    this.getExerciseData();
    this.getDirectData();
  },
  changeCatalog(e) {
    var page = this;
    let standard_id = e.currentTarget.dataset.id,
      standard_name = e.currentTarget.dataset.standard_name;
    page.setData({
      standard_id: standard_id
    });
    app.setPageTitle(standard_name);

    page.getResList();
    page.getExerciseData();
    page.getDirectData();
  },
  getResList() {
    let page = this;
    //  课件列表
    app.sendRequest({
      url: api.course.lesson_courseware_list,
      data: {
        standard_id: page.data.standard_id,
        type: 0,
        if_all: 1
      },
      success: function(res) {
        let coursewares = res.data.list || [];
        let video_coursewares = [],
          other_coursewares = [];
        if (coursewares.length > 0) {
          coursewares.map(courseware => {
            courseware.icon_type = courseware.url.split('.')[1];
            if (courseware.type == 2) {
              video_coursewares.push(courseware);
            } else {
              other_coursewares.push(courseware);
            }
          });
        }

        let current_video_url = '',
          courseware_id = 0;
        if (video_coursewares.length > 0) {
          // current_video_url = video_coursewares[0].url
          current_video_url = util.getResetVideo(video_coursewares[0].url);
          courseware_id = video_coursewares[0].courseware_id;
          video_coursewares[0].if_start = 1;
        }

        page.setData({
          current_courseware_id: courseware_id,
          other_coursewares: other_coursewares,
          video_coursewares: video_coursewares,
          current_video_url: current_video_url
        });
      }
    });
  },
  getDirectData() {
    var page = this;
    let current_curriculum_id = wx.getStorageSync('current_curriculum_id');
    if (current_curriculum_id != undefined) {
      //  课程大纲
      app.sendRequest({
        url: app.api.public.outline_directory,
        data: {
          curriculum_id: current_curriculum_id
        },
        success(directory_res) {
          if (
            directory_res.data != '' &&
            directory_res.data.list != undefined
          ) {
            // 设置数据
            page.setData({
              treeData: directory_res.data.list
            });
          } else {
            page.setData({
              msg: '暂无目录',
              treeData: []
            });
          }
        }
      });
    }
  },
  // 按钮触摸开始触发的事件
  touchStart: function(e) {
    this.touchStartTime = e.timeStamp;
  },

  // 按钮触摸结束触发的事件
  touchEnd: function(e) {
    this.touchEndTime = e.timeStamp;
  },
  multipleTap: function(e) {
    var that = this;
    // 控制点击事件在350ms内触发，加这层判断是为了防止长按时会触发点击事件
    if (that.touchEndTime - that.touchStartTime < 350) {
      // 当前点击的时间
      var currentTime = e.timeStamp;
      var lastTapTime = that.lastTapTime;
      // 更新最后一次点击时间
      that.lastTapTime = currentTime;

      // 如果两次点击时间在300毫秒内，则认为是双击事件
      if (currentTime - lastTapTime >= 300) {
        // 单击事件延时300毫秒执行，这和最初的浏览器的点击300ms延时有点像。
        that.lastTapTimeoutFunc = setTimeout(function() {
          wx.previewImage({
            current: e.currentTarget.id, // 当前显示图片的http链接
            urls: that.data.files // 需要预览的图片http链接列表
          });
        }, 300);
      }
    }
  },
  //长按删除图片
  longTap: function(e) {
    var page = this;
    if (page.data.if_commit == 2) {
      return false;
    }
    let index = parseInt(e.currentTarget.dataset.index);
    Dialog.confirm({
      title: '提示',
      message: '确定删除图片吗'
    }).then(() => {
      let files = page.data.files,
        picture_list = page.data.picture_list;
      files.map((f, i) => {
        if (i == index) {
          files.splice(i, 1);
        }
      });
      picture_list.map((p, i) => {
        if (i == index) {
          picture_list.splice(i, 1);
        }
      });
      page.setData({
        files: files,
        picture_list: picture_list
      });
    });
  },
  getExerciseData: function() {
    var page = this;
    //  习题课时
    app.sendRequest({
      url: api.course.lesson_question_list,
      data: {
        standard_id: page.data.standard_id
      },
      success: function(question_res) {
        if (question_res.data.length > 0) {
          app.sendRequest({
            url: api.course.student_curriculum_item_list,
            data: {
              if_all: 1,
              question_id: question_res.data[0].question_id
            },
            success: function(res) {
              if (res.data.list) {
                var question_total = res.data.list.length;
                // 设置数据
                var pics = res.data.picture_list || [];
                if (pics.length > 0) {
                  pics.map((p, i) => {
                    pics[i] = page.data.downloadUrl + '/' + p;
                  });
                }
                page.setData({
                  question_id: question_res.data[0].question_id,
                  question_total: question_total ? question_total : 0,
                  questions: res.data.list,
                  if_commit: res.data.if_commit,
                  picture_list: res.data.picture_list,
                  files: pics
                });
                page.preProcessData();
                page.processHtml();
              } else {
                // 无习题时标记学习完成
                app.sendRequest({
                  hideLoading: true,
                  method: 'POST',
                  header: {
                    token: wx.getStorageSync('access_token'),
                    'content-type': 'application/x-www-form-urlencoded'
                  },
                  data: { standard_id: page.data.standard_id },
                  url: app.api.course.study_tag,
                  success(res) {
                    wx.setStorageSync(
                      'current_complete_standard',
                      page.data.standard_id
                    );
                  }
                });

                page.setData({
                  questions: [],
                  question_total: 0
                });
              }
            }
          });
        } else {
          page.setData({
            questions: []
          });
        }
      }
    });
  },
  //html转wxml处理
  processHtml: function() {
    var page = this;
    var questions = page.data.questions;
    var stemArr = [];
    var analysisArr = [];

    //获取题干解析html总请求数
    var body_url_cnt = 0,
      body_url_load_cnt = 0;
    var analysis_url_cnt = 0,
      analysis_url_load_cnt = 0;
    questions.map(q => {
      if (q.stem_url != undefined && q.stem_url.length > 0) {
        body_url_cnt++;
      }
      if (q.analysis_url != undefined && q.analysis_url.length > 0) {
        analysis_url_cnt++;
      }
    });

    questions.map((q, index) => {
      if (q.stem_url != undefined && q.stem_url.length > 0) {
        util
          .get(page.data.question_html + '/' + q.stem_url)
          .then(function(res) {
            body_url_load_cnt++;
            questions[index].stem = res.data.replace(
              /\<img/gi,
              '<img style="max-width:100%;height:auto"'
            );
            if (body_url_load_cnt == body_url_cnt) {
              page.setData({
                questions: questions
              });
            }
          });
      } else {
        questions[index].stem = q.stem.replace(
          /\<img/gi,
          '<img style="max-width:100%;height:auto"'
        );
      }
      if (q.analysis_url != undefined && q.analysis_url.length > 0) {
        util
          .get(page.data.question_html + '/' + q.analysis_url)
          .then(function(res) {
            analysis_url_load_cnt++;
            questions[index].analysis = res.data.replace(
              /\<img/gi,
              '<img style="max-width:100%;height:auto"'
            );
            if (analysis_url_load_cnt == analysis_url_cnt) {
              page.setData({
                questions: questions
              });
            }
          });
      } else {
        questions[index].analysis = q.analysis.replace(
          /\<img/gi,
          '<img style="max-width:100%;height:auto"'
        );
      }

      // questions[index].seq = index;
      // //题干html转wxml
      // if (q.stem.length > 0) {
      //   stemArr[index] = q.stem;
      // } else {
      //   stemArr[index] = "";
      // }
      // WxParse.wxParse("stem" + index, "html", stemArr[index], page);
      // if (index === questions.length - 1) {
      //   WxParse.wxParseTemArray("stemTemArray", "stem", stemArr.length, page);
      // }
      // //解析html转wxml
      // if (q.analysis.length > 0) {
      //   analysisArr[index] = q.analysis;
      // } else {
      //   analysisArr[index] = "";
      // }
      // WxParse.wxParse("analysis" + index, "html", analysisArr[index], page);
      // if (index === questions.length - 1) {
      //   WxParse.wxParseTemArray(
      //     "analysisTemArray",
      //     "analysis",
      //     analysisArr.length,
      //     page
      //   );
      // }
    });

    page.setData({
      questions: questions
    });
  },
  //画面数据格式预处理
  preProcessData: function() {
    var page = this;
    var questions = page.data.questions;
    questions.map(q => {
      //多选题的情况,答案转数组
      if ((q.answer.length > 1 || q.student_answer.length > 1) && q.type == 1) {
        q.answer_str = q.answer;
        q.student_answer_str = q.student_answer;
        q.answer = q.answer.split('');
        q.student_answer = q.student_answer.split('');
      }
    });
    page.setData({
      questions: questions
    });
  },
  submit: function() {
    var page = this,
      item_list = [],
      list_tmp = page.data.questions;

    var keguan_ans_cnt = 0;
    var keguan_total_cnt = 0;
    var zhuguan_total_cnt = 0;
    for (var i = 0; i < list_tmp.length; i++) {
      var rightOrWrong = '1';
      //客观题处理
      if (list_tmp[i].answer.length > 0) {
        if (list_tmp[i].type == 1 || list_tmp[i].type == 2) {
          keguan_total_cnt++;
        }

        if (list_tmp[i].student_answer.length > 0) {
          keguan_ans_cnt++;

          //选择题的情况
          if (list_tmp[i].type == 1) {
            //单选题的情况
            if (list_tmp[i].answer.length == 1) {
              if (list_tmp[i].student_answer == list_tmp[i].answer) {
                rightOrWrong = '1';
              } else {
                rightOrWrong = '2';
              }
            } else {
              //多选题的情况
              if (
                list_tmp[i].student_answer.sort().toString() ==
                list_tmp[i].answer.sort().toString()
              ) {
                rightOrWrong = '1';
              } else {
                rightOrWrong = '2';
              }
              list_tmp[i].student_answer = list_tmp[i].student_answer.join('');
            }
          } else if (list_tmp[i].type == 2) {
            let ans = ['', 'true', 'false'];
            //判断题的情况
            if (list_tmp[i].student_answer == list_tmp[i].answer) {
              rightOrWrong = '1';
            } else {
              rightOrWrong = '2';
            }
          }

          item_list.push({
            uuid: list_tmp[i].uuid,
            answer: list_tmp[i].student_answer,
            if_right: parseInt(rightOrWrong)
          });
        }
      } else {
        //主观题
        zhuguan_total_cnt++;
        if (page.data.picture_list.length == 0) rightOrWrong = '0'; //未作答主观题
        item_list.push({
          uuid: list_tmp[i].uuid,
          answer: '',
          if_right: parseInt(rightOrWrong)
        });
      }
    }

    if (keguan_ans_cnt < keguan_total_cnt) {
      Dialog.alert({
        message: '客观题还未答完，无法“提交答案'
      });
      return false;
    }

    // if (zhuguan_total_cnt > 0) {
    // Dialog.confirm({
    //   title: "提示",
    //   message: "主观题还未作答，若图片没上传则默认为主观题全错。"
    // })
    //   .then(() => {
    var answer_json = {
      picture_list: page.data.picture_list,
      file_list: [],
      item_list: item_list
    };

    var param = {
      question_id: page.data.question_id,
      answer_json: JSON.stringify(answer_json)
    };
    //提交答案
    app.sendRequest({
      url: app.api.course.student_curriculum_submit,
      method: 'POST',
      header: {
        token: wx.getStorageSync('access_token'),
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: param,
      success: function(res) {
        Toast('提交成功！');
        // 学习完成
        app.sendRequest({
          hideLoading: true,
          method: 'POST',
          header: {
            token: wx.getStorageSync('access_token'),
            'content-type': 'application/x-www-form-urlencoded'
          },
          data: { standard_id: page.data.standard_id },
          url: app.api.course.study_tag,
          success(res) {
            wx.setStorageSync(
              'current_complete_standard',
              page.data.standard_id
            );
          }
        });
        page.getExerciseData();
        app.goTop();
      }
    });
    // }
    /*)
            .catch(() => {
              // on cancel
            });
        } else {
          var answer_json = {
            picture_list: page.data.picture_list,
            file_list: [],
            item_list: item_list
          };

          var param = {
            question_id: page.data.question_id,
            answer_json: JSON.stringify(answer_json)
          };
          //提交答案
          app.sendRequest({
            url: app.api.course.student_curriculum_submit,
            method: 'POST',
            header: {
              'token': wx.getStorageSync("access_token"),
              'content-type': 'application/x-www-form-urlencoded'
            },
            data: param,
            success: function (res) {
              console.log(res)
              Toast('提交成功！');
              page.getExerciseData();
            }
          })
        }*/
  },
  chooseImage: function(e) {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFiles = res.tempFiles;
        that.setData({
          files: that.data.files.concat(tempFiles[0].path)
        });

        that.uploadQiniu(tempFiles);
      }
    });
  },
  previewImage: function(e) {},
  /**
   * 图片上传
   */
  uploadQiniu: function(tempFilePaths) {
    var that = this;
    wx.uploadFile({
      // url: app.api.xh.uploadUrl,
      url: app.api.xh.uploadDomain,
      name: 'file',
      filePath: tempFilePaths[0].path,
      header: {
        'Content-Type': 'multipart/form-data',
        token: wx.getStorageSync('access_token')
      },
      // formData: {
      //   token: that.data.uploadToken
      // },
      success: function(res) {
        let data = JSON.parse(res.data);
        var picture_list = that.data.picture_list;
        // picture_list.push({url: data.key, name: data.key, size: tempFilePaths[0].size});
        picture_list.push(data.data.url);
        that.setData({
          picture_list: picture_list
        });
      },
      fail: function(res) {}
    });
  },
  toggleCatalog: function(e) {
    var page = this;
    var expand_status = e.currentTarget.dataset.expand;
    var id = e.currentTarget.dataset.id,
      questions = page.data.questions;

    for (var i = 0; i < questions.length; i++) {
      if (questions[i].uuid == id) {
        questions[i].expand = !expand_status;
      }
    }
    page.setData({
      questions: questions
    });
  },
  //单选题处理
  onChange(e) {
    var page = this,
      select_qid = e.currentTarget.dataset.id,
      select_option = e.detail,
      questions = page.data.questions;

    //已提交的情况间接实现只读效果
    if (page.data.if_commit == 2) {
      return;
    }

    for (var i = 0; i < questions.length; i++) {
      if (questions[i].uuid == select_qid) {
        questions[i].student_answer = select_options[select_option];
      }
    }
    page.setData({
      questions: questions
    });
  },
  //判断题处理
  onPDChange(e) {
    var page = this,
      select_qid = e.currentTarget.dataset.id,
      select_option = e.detail,
      questions = page.data.questions;

    //已提交的情况间接实现只读效果
    if (page.data.if_commit == 2) {
      return;
    }

    for (var i = 0; i < questions.length; i++) {
      if (questions[i].uuid == select_qid) {
        questions[i].student_answer = select_option;
      }
    }
    page.setData({
      questions: questions
    });
  },
  //多选题处理
  onCBChange(e) {
    var page = this,
      select_qid = e.currentTarget.dataset.id,
      questions = page.data.questions;

    //已提交的情况间接实现只读效果
    if (page.data.if_commit == 2) {
      return;
    }

    for (var i = 0; i < questions.length; i++) {
      if (questions[i].uuid == select_qid) {
        questions[i].student_answer = e.detail;
      }
    }
    page.setData({
      questions: questions
    });
  },
  changeVideo(e) {
    var file_url = e.currentTarget.dataset.url;
    var courseware_id = e.currentTarget.dataset.id;
    var page = this;

    page.setData({
      current_courseware_id: courseware_id,
      current_video_url: util.getResetVideo(file_url)
    });
    //  更新视频课件学习进度
    app.sendRequest({
      hideLoading: true,
      url: api.course.lesson_courseware_info,
      data: {
        courseware_id: courseware_id
      },
      success(res) {
        let video_coursewares = page.data.video_coursewares;
        video_coursewares.map(course_ware => {
          if (course_ware.courseware_id == courseware_id) {
            course_ware.if_start = 1;
          }
        });
        page.setData({
          video_coursewares: video_coursewares
        });
      }
    });
  },
  toDetail: function(e) {
    var type = e.currentTarget.dataset.type;
    var file_url = e.currentTarget.dataset.url;
    var courseware_id = e.currentTarget.dataset.id;
    var name = e.currentTarget.dataset.name;
    var page = this;

    //  更新非视频课件学习进度
    app.sendRequest({
      hideLoading: true,
      url: api.course.lesson_courseware_info,
      data: {
        courseware_id: courseware_id
      },
      success(res) {
        let other_coursewares = page.data.other_coursewares;
        other_coursewares.map(course_ware => {
          if (course_ware.courseware_id == courseware_id) {
            course_ware.if_start = 1;
          }
        });
        page.setData({
          other_coursewares: other_coursewares
        });
      }
    });

    switch (type) {
      case 'word':
      case 'excel':
      case 'ppt':
      case 'pdf':
        page.setData({
          currentFileUrl: file_url
        });
        page.openOffice();
        break;
      case 'music':
        //跳转音频播放页
        wx.navigateTo({
          url:
            '/pages/preview/preview?type=' +
            type +
            '&file_url=' +
            file_url +
            '&name=' +
            name
        });
        break;
      case 'img':
        wx.previewImage({
          current: page.data.downloadUrl + file_url,
          urls: [page.data.downloadUrl + file_url]
        });
        break;
      case 'video':
        //跳转视频播放页
        wx.navigateTo({
          url:
            '/pages/preview/preview?type=' +
            type +
            '&file_url=' +
            file_url +
            '&name=' +
            name
        });
        break;
      case 'flash':
      case 'other':
      default:
        wx.navigateTo({
          url:
            '/pages/preview/preview?type=' +
            type +
            '&file_url=' +
            file_url +
            '&name=' +
            name
        });
        break;
    }
  },
  //打开office文档
  openOffice: function() {
    var page = this;
    var url = page.data.currentFileUrl;
    Toast.loading({
      duration: 0,
      forbidClick: true,
      mask: true,
      message: '文档加载中...'
    });
    wx.downloadFile({
      // 示例 url，并非真实存在
      url: page.data.downloadUrl + url,
      success: function(res) {
        Toast.clear();
        const filePath = res.tempFilePath;
        wx.openDocument({
          filePath: filePath,
          success: function(res) {}
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let page = this;
    // 设置content高度
    wx.getSystemInfo({
      success: function(res) {
        page.setData({
          // second部分高度 = 窗口可使用高度
          content_height: res.windowHeight - 280
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {}
});
